package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.service.WmChannelService;
import com.heima.wemedia.service.WmNewsMaterialService;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 频道信息表 服务实现类
 * </p>
 *
 * @author itheima
 */
@Slf4j
@Service
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements WmChannelService {

    @Autowired
    private WmNewsService wmNewsService;

    @Autowired
    private WmNewsMaterialService wmNewsMaterialService;
    @Override
    public ResponseResult downOrUp(WmNewsDto wmNewsDto) {
        if (wmNewsDto.getId()==null){
            return ResponseResult.errorResult(501,"文章id不可缺少");
        }
        WmNews byId = wmNewsService.getById(wmNewsDto.getId());
        if (byId==null){
            return ResponseResult.errorResult(1002,"文章不存在");
        }
        Date date = new Date();
        Date publishTime = byId.getPublishTime();
        if (publishTime.after(date)){
            return ResponseResult.okResult(501,"当前文章不在发布状态,不能上下架");
        }
        byId.setEnable(wmNewsDto.getEnable().shortValue());

        wmNewsService.updateById(byId);

        return ResponseResult.okResult("成功");
    }

    @Override
    public ResponseResult delNews(Integer id) {
        if (id==null){
            return ResponseResult.errorResult(501,"文章id不可缺少");
        }
        WmNews byId = wmNewsService.getById(id);
        if (byId==null){
            return ResponseResult.errorResult(1002,"文章不存在");
        }

        Date date = new Date();
        Date publishTime = byId.getPublishTime();
        if (publishTime.before(date)){
            if (byId.getEnable()==1){
                return ResponseResult.errorResult(501,"文章已上架不能删除");
            }
        }


        wmNewsService.removeById(id);
        LambdaUpdateWrapper<WmNewsMaterial> wmNewsMaterialLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        wmNewsMaterialLambdaUpdateWrapper.eq(WmNewsMaterial::getNewsId,id);
        wmNewsMaterialService.remove(wmNewsMaterialLambdaUpdateWrapper);
        return ResponseResult.okResult("操作成功");
    }
}
